package com.lh.web.ctrl;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lh.biz.IProductBiz;
import com.lh.biz.dto.in.product.SearchInDto;
import com.lh.component.data.factory.CategoryFactory;
import com.lh.ctrl.BaseCtrl;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-5-23 下午10:28:55
 */
@Controller
@RequestMapping("/so")
public class SearchProduct extends BaseCtrl {

	@Resource
	private CategoryFactory categoryFactory;

	@Resource
	private IProductBiz productBiz;

	@ModelAttribute
	public void init(Model model) {
		model.addAttribute("categoryMap", categoryFactory.getMap());
		model.addAttribute("categoryList", categoryFactory.getList());
	}

	@RequestMapping
	public String search(@ModelAttribute("keywords") String keywords, Model model) {
		SearchInDto inDto = new SearchInDto();
		inDto.setKeywords(keywords);
		model.addAttribute("out", productBiz.search(inDto));
		return "/product/search";
	}

	@RequestMapping("/{cId}-{cName}-{keywords}-{properties}-{minPrice}-{maxPrice}-{sort}-{index}")
	public String search(@ModelAttribute @PathVariable Long cId, @PathVariable String cName, @ModelAttribute @PathVariable String keywords,
			@ModelAttribute @PathVariable String properties, @ModelAttribute @PathVariable Double minPrice, @ModelAttribute @PathVariable Double maxPrice,
			@ModelAttribute @PathVariable String sort,@ModelAttribute @PathVariable Integer index, String p1, String p2, Model model) {
		if (p1 != null) {
			if (StringUtils.isBlank(p1)) {
				minPrice = null;
			} else {
				try {
					minPrice = Double.parseDouble(p1);
				} catch (NumberFormatException e) {
				}
			}
			model.addAttribute("minPrice", minPrice);
		}
		if (p2 != null) {
			if (StringUtils.isBlank(p2)) {
				maxPrice = null;
			} else {
				try {
					maxPrice = Double.parseDouble(p2);
				} catch (NumberFormatException e) {
				}
			}
			model.addAttribute("maxPrice", maxPrice);
		}
		SearchInDto inDto = new SearchInDto();
		inDto.setCategoryId(cId);
		inDto.setKeywords(keywords);
		inDto.setProperties(properties);
		inDto.setMinPrice(minPrice);
		inDto.setMaxPrice(maxPrice);
		inDto.setBeginIndex(index);
		inDto.setSort(sort);
		model.addAttribute("out", productBiz.search(inDto));
		return "/product/search";
	}

}
